package com.mcintyret.site.users.database;

import com.mcintyret.site.users.User;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * User: tommcintyre
 * Date: 3/29/12
 */

@Configuration
public class UsersDatabaseConfig {

    @Value("${common.database.driverClassName}")
    private String databaseDriverClassName;
    @Value("${users.database.url}")
    private String databaseUrl;
    @Value("${users.database.username}")
    private String databaseUsername;
    @Value("${users.database.password}")
    private String databasePassword;

    @Bean
    public DataSource usersDataSource() {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriverClassName);
        basicDataSource.setUrl(databaseUrl);
        basicDataSource.setUsername(databaseUsername);
        basicDataSource.setPassword(databasePassword);
        return basicDataSource;
    }

    @Bean
    public org.hibernate.cfg.Configuration localSessionFactoryBuilder() {
        return new LocalSessionFactoryBuilder(usersDataSource())
                .addAnnotatedClasses(User.class)
                .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
                .setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
    }

    @Bean
    public SessionFactory usersSessionFactory() {
        return localSessionFactoryBuilder().buildSessionFactory();
    }

    @Bean
    public PlatformTransactionManager usersTransactionManager() {
        return new HibernateTransactionManager(usersSessionFactory());
    }

}
